package top.saplf.sileny.util

import android.graphics.*
import android.graphics.drawable.Drawable
import android.util.Base64
import java.io.ByteArrayOutputStream

/**
 * @author Saplf on 17/4/9
 */

fun base64ToBitmap(content: String): Bitmap {
    val byteArray = base64ToByteArray(content)
    return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
}

fun base64ToByteArray(content: String): ByteArray = Base64.decode(content, Base64.DEFAULT)

fun bitmapToBase64(bitmap: Bitmap): String {
    return Base64.encodeToString(bitmapToByteArray(bitmap), Base64.DEFAULT)
}

fun bitmapToByteArray(bitmap: Bitmap): ByteArray {
    val bos = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.WEBP, 100, bos)
    return bos.toByteArray()
}

fun drawableToBitmap(drawable: Drawable): Bitmap =
        with(drawable) {
            val bitmap = Bitmap.createBitmap(
                    intrinsicWidth, intrinsicHeight,
                    if (opacity != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565
            )
            val canvas = Canvas(bitmap)
            bounds = Rect(0, 0, intrinsicWidth, intrinsicHeight)
            draw(canvas)
            bitmap
        }

fun drawableToBase64(drawable: Drawable): String
        = bitmapToBase64(drawableToBitmap(drawable))